<template>
  <a-card :bordered="false" :title="$route.meta.title" :bodyStyle="{ padding: '12px' }">
    <a-button v-auth:add slot="extra" type="primary" icon="plus" @click="$refs.form.create()">新建</a-button>
    <a-table rowKey="id" size="middle" :scroll="scroll" :loading="loading" :columns="columns" :dataSource="treeData" :pagination="pagination" default-expand-all-rows>
      <div slot="action" slot-scope="text,record" class="table-action">
        <span v-auth:edit>
          <a @click.stop="$refs.form.update(record)">修改</a>
          <a-divider type="vertical" />
        </span>
        <a v-auth:del @click.stop="onDelete(record)" class="delete">删除</a>
      </div>
    </a-table>
    <sjht-org-form ref="form" :parent-org="dataSource" @success="loadData" />
  </a-card>
</template>
<script>
import { table, tableMore } from '@/utils/mixins'
import { listToTree } from '@/utils/common'
import { GetOrgList, DeleteOrg } from '@/api/manage/org'
import OrgForm from './modules/form'
export default {
  name: 'OrgList', //组织机构管理
  mixins: [table, tableMore],
  components: {
    [OrgForm.name]: OrgForm
  },
  data() {
    return {
      pagination: false,
      columns: [
        { title: '组织名称', dataIndex: 'orgName', width: 200 },
        { title: '组织描述', dataIndex: 'orgDesc', width: 200 },
        { title: '状态', dataIndex: 'status', width: 75, align: 'center', customRender: t => (t ? '启用' : '停用') },
        { title: '排序', dataIndex: 'sort', width: 75, align: 'center' },
        { title: '创建时间', dataIndex: 'createTime', width: 145 },
        { title: '操作', key: 'operation', width: 95, align: 'center', scopedSlots: { customRender: 'action' } }
      ]
    }
  },
  computed: {
    treeData: function () {
      return listToTree(this.dataSource, null, 'parentId')
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 加载数据
    loadData() {
      this.loading = true
      GetOrgList()
        .then(res => {
          this.dataSource = res
        })
        .catch(err => {
          this.dataSource = []
          this.$message.error(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    //删除
    onDelete(rec) {
      if (this.dataSource.some(x => x.parentId == rec.id)) {
        this.$message.error(`请先删除【${rec.orgName}】所有下级组织`)
        return false
      }
      this.$confirm({
        title: '确定删除组织机构吗？',
        content: `删除【${rec.orgName}】组织机构，请谨慎操作。`,
        okType: 'danger',
        onOk: () => {
          const { $message } = this
          this.loading = true
          return DeleteOrg({ id: rec.id })
            .then(() => {
              $message.success('删除成功')
              this.loadData()
            })
            .catch(err => {
              $message.error(err)
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>